import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, Descriptions, Popconfirm, InputNumber, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { request } from 'umi';

const { Option } = Select;
const { TextArea } = Input;

// 获取包厢列表
const fetchRooms = async (params) => {
    return request('/api/v1/store/room', {
        method: 'GET',
        params,
    });
};

// 获取包厢详情
const fetchRoomDetail = async (id) => {
    return request(`/api/v1/store/room/${id}`, {
        method: 'GET',
    });
};

// 创建包厢
const createRoom = async (data) => {
    return request('/api/v1/store/room', {
        method: 'POST',
        data,
    });
};

// 更新包厢
const updateRoom = async (data) => {
    return request('/api/v1/store/room', {
        method: 'PUT',
        data,
    });
};

// 删除包厢
const deleteRoom = async (id) => {
    return request(`/api/v1/store/room/${id}`, {
        method: 'DELETE',
    });
};

// 获取门店列表
const fetchStores = async () => {
    return request('/api/v1/store', {
        method: 'GET',
        params: { pageSize: 100, status: 1 },
    });
};

const StoreRoom = () => {
    const [rooms, setRooms] = useState([]);
    const [stores, setStores] = useState([]);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const [roomForm] = Form.useForm();
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [searchParams, setSearchParams] = useState({});
    const [detailVisible, setDetailVisible] = useState(false);
    const [formVisible, setFormVisible] = useState(false);
    const [currentRoom, setCurrentRoom] = useState(null);
    const [formTitle, setFormTitle] = useState('创建包厢');

    // 获取包厢列表
    const fetchRoomList = async () => {
        try {
            setLoading(true);
            const res = await fetchRooms({
                page: pagination.current,
                pageSize: pagination.pageSize,
                ...searchParams,
            });
            if (res.success) {
                setRooms(res.data.list || []);
                setPagination({
                    ...pagination,
                    total: res.data.total,
                });
            } else {
                message.error(res.message || '获取包厢列表失败');
            }
        } catch (error) {
            console.error('获取包厢列表出错:', error);
            message.error('获取包厢列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取门店列表
    const fetchStoreList = async () => {
        try {
            const res = await fetchStores();
            if (res.success) {
                setStores(res.data.list || []);
            } else {
                message.error(res.message || '获取门店列表失败');
            }
        } catch (error) {
            console.error('获取门店列表出错:', error);
            message.error('获取门店列表失败');
        }
    };

    useEffect(() => {
        fetchRoomList();
        fetchStoreList();
    }, [pagination.current, pagination.pageSize, searchParams]);

    // 查看包厢详情
    const handleViewDetail = async (record) => {
        try {
            setLoading(true);
            const res = await fetchRoomDetail(record.id);
            if (res.success) {
                setCurrentRoom(res.data);
                setDetailVisible(true);
            } else {
                message.error(res.message || '获取包厢详情失败');
            }
        } catch (error) {
            console.error('获取包厢详情出错:', error);
            message.error('获取包厢详情失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理添加包厢
    const handleAdd = () => {
        setFormTitle('创建包厢');
        setCurrentRoom(null);
        roomForm.resetFields();
        roomForm.setFieldsValue({
            status: true,
        });
        setFormVisible(true);
    };

    // 处理编辑包厢
    const handleEdit = (record) => {
        setFormTitle('编辑包厢');
        setCurrentRoom(record);
        roomForm.resetFields();
        roomForm.setFieldsValue({
            name: record.name,
            storeId: record.storeId,
            capacity: record.capacity,
            price: record.price / 100,
            minCharge: record.minCharge / 100,
            description: record.description,
            status: record.status === 1,
        });
        setFormVisible(true);
    };

    // 处理删除包厢
    const handleDelete = async (id) => {
        try {
            setLoading(true);
            const res = await deleteRoom(id);
            if (res.success) {
                message.success('删除包厢成功');
                fetchRoomList();
            } else {
                message.error(res.message || '删除包厢失败');
            }
        } catch (error) {
            console.error('删除包厢出错:', error);
            message.error('删除包厢失败');
        } finally {
            setLoading(false);
        }
    };

    // 提交表单
    const handleFormSubmit = async () => {
        try {
            const values = await roomForm.validateFields();
            setLoading(true);

            // 转换金额为分
            values.price = Math.round(values.price * 100);
            values.minCharge = Math.round(values.minCharge * 100);

            // 设置状态
            values.status = values.status ? 1 : 0;

            let res;
            if (currentRoom) {
                // 更新
                res = await updateRoom({
                    id: currentRoom.id,
                    ...values,
                });
            } else {
                // 创建
                res = await createRoom(values);
            }

            if (res.success) {
                message.success(`${currentRoom ? '更新' : '创建'}包厢成功`);
                setFormVisible(false);
                fetchRoomList();
            } else {
                message.error(res.message || `${currentRoom ? '更新' : '创建'}包厢失败`);
            }
        } catch (error) {
            console.error(`${currentRoom ? '更新' : '创建'}包厢出错:`, error);
            message.error(`${currentRoom ? '更新' : '创建'}包厢失败`);
        } finally {
            setLoading(false);
        }
    };

    // 处理搜索
    const handleSearch = (values) => {
        const params = {};
        if (values.name) {
            params.name = values.name;
        }
        if (values.storeId) {
            params.storeId = values.storeId;
        }
        if (values.status !== undefined) {
            params.status = values.status;
        }

        setSearchParams(params);
        setPagination({
            ...pagination,
            current: 1,
        });
    };

    // 处理重置
    const handleReset = () => {
        form.resetFields();
        setSearchParams({});
        setPagination({
            ...pagination,
            current: 1,
        });
    };

    // 表格列定义
    const columns = [
        {
            title: '包厢名称',
            dataIndex: 'name',
            key: 'name',
            width: 150,
        },
        {
            title: '所属门店',
            dataIndex: 'storeName',
            key: 'storeName',
            width: 150,
        },
        {
            title: '容纳人数',
            dataIndex: 'capacity',
            key: 'capacity',
            width: 100,
        },
        {
            title: '包厢价格',
            dataIndex: 'price',
            key: 'price',
            width: 120,
            render: (text) => `¥${(text / 100).toFixed(2)}/小时`,
        },
        {
            title: '最低消费',
            dataIndex: 'minCharge',
            key: 'minCharge',
            width: 120,
            render: (text) => `¥${(text / 100).toFixed(2)}`,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status) => (
                <Tag color={status === 1 ? 'green' : 'red'}>
                    {status === 1 ? '可用' : '不可用'}
                </Tag>
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            width: 180,
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewDetail(record)}
                    >
                        详情
                    </Button>
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定要删除此包厢吗？"
                        onConfirm={() => handleDelete(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button
                            type="link"
                            icon={<DeleteOutlined />}
                            danger
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    // 处理表格变化
    const handleTableChange = (pagination, filters, sorter) => {
        setPagination(pagination);
    };

    return (
        <PageContainer>
            <Card style={{ marginBottom: 24 }}>
                <Form
                    form={form}
                    layout="inline"
                    onFinish={handleSearch}
                    style={{ marginBottom: 24 }}
                >
                    <Form.Item name="name" label="包厢名称">
                        <Input placeholder="请输入包厢名称" style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item name="storeId" label="所属门店">
                        <Select placeholder="请选择门店" style={{ width: 200 }} allowClear>
                            {stores.map(store => (
                                <Option key={store.id} value={store.id}>{store.name}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="status" label="状态">
                        <Select placeholder="请选择状态" style={{ width: 200 }} allowClear>
                            <Option value={1}>可用</Option>
                            <Option value={0}>不可用</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                            <Button onClick={handleReset}>重置</Button>
                        </Space>
                    </Form.Item>
                </Form>

                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                        创建包厢
                    </Button>
                </div>

                <Table
                    columns={columns}
                    dataSource={rooms}
                    rowKey="id"
                    loading={loading}
                    pagination={pagination}
                    onChange={handleTableChange}
                    scroll={{ x: 1200 }}
                />
            </Card>

            {/* 包厢详情弹窗 */}
            <Modal
                title="包厢详情"
                visible={detailVisible}
                onCancel={() => setDetailVisible(false)}
                footer={null}
                width={700}
            >
                {currentRoom && (
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="包厢名称" span={2}>{currentRoom.name}</Descriptions.Item>
                        <Descriptions.Item label="所属门店">{currentRoom.storeName}</Descriptions.Item>
                        <Descriptions.Item label="状态">
                            <Tag color={currentRoom.status === 1 ? 'green' : 'red'}>
                                {currentRoom.status === 1 ? '可用' : '不可用'}
                            </Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="容纳人数">{currentRoom.capacity}人</Descriptions.Item>
                        <Descriptions.Item label="包厢价格">{`¥${(currentRoom.price / 100).toFixed(2)}/小时`}</Descriptions.Item>
                        <Descriptions.Item label="最低消费">{`¥${(currentRoom.minCharge / 100).toFixed(2)}`}</Descriptions.Item>
                        <Descriptions.Item label="创建时间">{currentRoom.createdAt}</Descriptions.Item>
                    </Descriptions>
                )}
            </Modal>
            {/* 新增/编辑包厢弹窗 */}
            <Modal
                title={formTitle}
                visible={formVisible}
                onCancel={() => setFormVisible(false)}
                footer={null}
                width={700}
                destroyOnClose
            >
                <Form
                    form={roomForm}
                    name="roomForm"
                    onFinish={handleFormSubmit}
                    autoComplete="off"
                    layout="vertical"
                    initialValues={currentRoom}
                    preserve={false} // 重置表单时，重置到初始值，而不是清空
                >
                    <Form.Item
                        label="包厢名称"
                        name="name"
                        rules={[{ required: true, message: '请输入包厢名称' }]}
                    >
                        <Input placeholder="请输入包厢名称" />
                    </Form.Item>
                    <Form.Item
                        label="所属门店"
                        name="storeId"
                        rules={[{ required: true, message: '请选择所属门店' }]}
                    >
                        <Select placeholder="请选择所属门店">
                            {stores.map(store => (
                                <Option key={store.id} value={store.id}>{store.name}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="容纳人数"
                        name="capacity"
                        rules={[{ required: true, message: '请输入容纳人数' }]}
                    >
                        <InputNumber placeholder="请输入容纳人数" />
                    </Form.Item>
                    <Form.Item
                        label="包厢价格"
                        name="price"
                        rules={[{ required: true, message: '请输入包厢价格' }]}
                    >
                        <InputNumber placeholder="请输入包厢价格" min={0} precision={2} />
                    </Form.Item>
                    <Form.Item
                        label="最低消费"
                        name="minCharge"
                        rules={[{ required: true, message: '请输入最低消费' }]}
                    >
                        <InputNumber placeholder="请输入最低消费" min={0} precision={2} />
                    </Form.Item>
                    <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                            <Button onClick={() => setFormVisible(false)}>取消</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </PageContainer>
    );
};
export default StoreRoom;